package portal.engine;

import beans.HttpConfig;
import beans.HttpResult;
import beans.RunningTask;
import dao.TaskDao;
import engine.BIEngine0_1.TaskThread;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.util.List;
import java.util.Map;

public class ListenerOfProjectStart implements ServletContextListener {
    private UpdateJobThread updateJobThread;

    /**
     * tomcat关闭时执行
     * @param e
     */
    public void contextDestroyed(ServletContextEvent e) {
        //销毁更新调度作业
        if (updateJobThread != null && updateJobThread.isInterrupted()) {
            updateJobThread.interrupt();
        }
        //将正在运行的任务序列化到数据库
        boolean isSuccess = runningTaskToDB();

    }

    /**
     * tomcat启动时执行
     * @param e
     */
    public void contextInitialized(ServletContextEvent e) {
        //启动作业更新线程，定时更新调度作业详情
//        if (updateJobThread == null) {
//            updateJobThread = new UpdateJobThread();
//            updateJobThread.start(); // servlet 上下文初始化时启动 socket
//        }
//
//        //将因tomcat关闭而序列化到数据库中的任务，添加到任务线程池中
//        boolean isSuccess = DBToRunningTask();
    }

    private boolean runningTaskToDB(){
        Map<String, TaskThread> taskMap = RunningTask.TASKMAP.getTaskMap();
        boolean isSuccess = true;
        //遍历线程池中每一个子任务
        for(Map.Entry<String, TaskThread> entry : taskMap.entrySet()){
            System.out.println("tomcat关闭任务池任务hash"+entry.getKey());
            TaskThread task = entry.getValue();
            isSuccess = isSuccess&task.disconnectTask();
        }
        return isSuccess;
    }

    private boolean DBToRunningTask(){
        /**
         * 从服务器获取token
         */
        HttpResult tokenResult = JobOperator.getToken(HttpConfig.userName, HttpConfig.passWord);
        boolean isSuccess = true;
        if (tokenResult.isResult()) {
            String token = tokenResult.getMessage();
            List<Object> taskThreads = new TaskDao().getDisconnectTaskThread();
            //将任务全部放入线程池
            for (Object one : taskThreads) {
                TaskThread task = (TaskThread) one;
                RunningTask.TASKMAP.setTask(task.runningTaskBean.getTaskHash(), task);
                System.out.println("重启任务id"+task.runningTaskBean.getTaskHash());
                //将一些因tomcat断开而调用JobCallBack失败的任务重新执行
                isSuccess = isSuccess & task.connectTask(token);
            }
        }else {
             isSuccess = false;
        }
        return isSuccess;
    }

}
